package com.lw.leetcode.arr;

import java.util.Arrays;

/**
 * 922. 按奇偶排序数组 II
 */
public class SortArrayByParityII {

    public static void main(String[] args) {
        SortArrayByParityII test = new SortArrayByParityII();
//        int[] arr = {3,1,4,2};
        int[] arr = {4,2,5,7};
        int[] ints = test.sortArrayByParityII(arr);
        System.out.println(Arrays.toString(ints));
    }

    public int[] sortArrayByParityII(int[] nums) {
        int length = nums.length;
        int a = 0;
        int b = 1;

        while (true) {
            int p = -1;
            int q = -1;
            for (int i = a; i < length; i = i + 2) {
                if ((nums[i] & 1) != 0) {
                    p = i;
                    a = i + 2;
                    break;
                }
            }

            for (int i = b; i < length; i = i + 2) {
                if ((nums[i] & 1) != 1) {
                    q = i;
                    b = i + 2;
                    break;
                }
            }

            if (p == -1) {
                break;
            }
            int value = nums[p];
            nums[p] = nums[q];
            nums[q] = value;
        }
        return nums;
    }

}
